<?php

// This is a PLUGIN TEMPLATE.

// Copy this file to a new name like abc_myplugin.php.  Edit the code, then
// run this file at the command line to produce a plugin for distribution:
// $ php abc_myplugin.php > abc_myplugin-0.1.txt

// Plugin name is optional.  If unset, it will be extracted from the current
// file name. Uncomment and edit this line to override:
$plugin['name'] = 'wyn_email_publish';

$plugin['version'] = '0.2';
$plugin['author'] = 'wayne';
$plugin['author_uri'] = 'http://www.gopherwood.info';
$plugin['description'] = 'Send mails to indicated addresses when you  publish a new post. You can use it sync your txp blog and your live space or blogger.';

// Plugin types:
// 0 = regular plugin; loaded on the public web side only
// 1 = admin plugin; loaded on both the public and admin side
// 2 = library; loaded only when include_plugin() or require_plugin() is called
$plugin['type'] = 1; 


@include_once('../zem_tpl.php');

if (0) {
?>
# --- BEGIN PLUGIN HELP ---
<h3>wyn_email_publish</h3>
<ol>
  <li><strong>Description</strong><br />
    When you publish a new post, this plugin will mail it to everywhere (email address of course :D) you want.
That means, you can publish the post onto other BSPs, which support email publish feature (like live space, or blogger), just as the same time you publish on textpattern.
  </li>
  <li><strong>History</strong><br />
    <ul>
      <li>0.2: Add admin config panel, you can not only set the email addresses here, but also customize the content of mail</li>
      <li>0.1: Initialize Release, just has basal function, a little troublesome to use</li>
    </ul>
  </li>
  <li><strong>Usage</strong><br />
    <ul>
      <li>Install and active it, and of course, set up your email publish function of your BSPs.</li>
      <li>Go to extenstion -&gt; Email Publish</li>
      <li>Now you can set the mail address, use ';' to separator if you have more than one address</li>
      <li>Set the title and body of mail, you can use the tag %title%, %body%, %author% and %link% to replace the title
, the content, the author name and the link of the article. (NOTICE: %link% and %body% are NOT allowed in mail title)</li>
      <li>Go to write a new post to introduce this little thing :D</li>
    </ul>
  </li>
</ol>

# --- END PLUGIN HELP ---
<?php
}

# --- BEGIN PLUGIN CODE ---

if (@txpinterface == 'admin') {
	add_privs ("wyn_email_publish", '1,2');
	register_callback ('wyn_email_publish', 'article', 'edit');
	register_callback ('wyn_email_publish_get_mark', 'article', 'edit', 1);

	/* for admin config */
	register_tab ("extensions", "wyn_email_publish", "Email Publish");
	register_callback ("wyn_email_publish_config", "wyn_email_publish");
}

function wyn_email_publish_get_mark ($event, $step) {
	if(!empty($GLOBALS['ID'])) {
		$ID = $GLOBALS['ID'];
	} else {
		$ID = gps ('ID');
	}

	$article = safe_row("ID, Status", "textpattern", "ID=$ID");
	extract ($article);
	$GLOBALS['OldStatus'] = fetch ('Status', 'textpattern', 'ID', $ID);
}

function wyn_email_publish ($event, $step) {
	global $wyn_email_publish_address, $wyn_email_publish_title, $wyn_email_publish_body;

	if (!isset ($wyn_email_publish_address)) {
		return;
	}

	if(!empty($GLOBALS['ID'])) {
		$ID = $GLOBALS['ID'];
	} else {
		$ID = gps ('ID');
	}

	$article = safe_row ("ID, Status, Title, Body_html, AuthorID", "textpattern", "ID=$ID");
	extract ($article);

	if (4 <= $Status && (empty ($GLOBALS['OldStatus']) || $GLOBALS['OldStatus'] < 4)) {
		/* link and body is no allowed in title */
		$th = preg_replace ('/%title%/', $Title, $wyn_email_publish_title);
		$th = preg_replace ('/%author%/', get_author_name ($AuthorID), $th);

		$body = preg_replace ('/%title%/', $Title, $wyn_email_publish_body);
		$body = preg_replace ('/%author%/', get_author_name ($AuthorID), $body);
		$body = preg_replace ('/%link%/', permlinkurl_id ($ID), $body);
		$body = preg_replace ('/%body%/', $Body_html, $body);

		/* Get email address */
		$addresses = split (';', $wyn_email_publish_address);
		foreach ($addresses as $address) {
			if (trim ($address) != '') {
				txpHtmlMail (trim ($address), $th, $body);
			}
		}
	}
}

function txpHtmlMail($to_address, $subject, $body, $reply_to = null) {
	global $txp_user, $prefs;

	if (isset($txp_user))  {
		extract(safe_row('RealName, email', 'txp_users', "name = '".doSlash($txp_user)."'"));
	} else {
		extract(safe_row('RealName, email', 'txp_users', "email = '".doSlash($to_address)."'"));
	}

	if ($prefs['override_emailcharset'] and is_callable('utf8_decode')) {
		$charset = 'ISO-8859-1';
		$RealName = utf8_decode($RealName);
		$subject = utf8_decode($subject);
		$body = utf8_decode($body);
	} else {
		$charset = 'UTF-8';
	}

	$RealName = encode_mailheader(strip_rn($RealName), 'phrase');
	$subject = encode_mailheader(strip_rn($subject), 'text');
	$email = strip_rn($email);

	if (!is_null($reply_to)) {
		$reply_to = strip_rn($reply_to);
	}

	if (!is_callable('mail')) {
		return false;
	} else {
		$sep = !is_windows() ? "\n" : "\r\n";
		$body = str_replace("\r\n", "\n", $body);
		$body = str_replace("\r", "\n", $body);
		$body = str_replace("\n", $sep, $body);
		return mail($to_address, $subject, $body,
				"From: $RealName <$email>".
				$sep.'Reply-To: '.( isset($reply_to) ? $reply_to : "$RealName <$email>" ).
				$sep.'X-Mailer: Textpattern'.
				$sep.'Content-Transfer-Encoding: 8bit'.
				$sep.'Content-Type: text/html; charset="'.$charset.'"'.
				$sep
			   );
	}
}

function wyn_email_publish_config ($event, $step) {
	global $prefs, $wyn_email_publish_address, $wyn_email_publish_title, $wyn_email_publish_body;

	$notify = '';

	if (ps ('save')) {
		/* Save */
		$notify = "Preferences Saved";
		$wyn_email_publish_address = ps ('wyn_email_publish_address');
		$wyn_email_publish_title = ps ('wyn_email_publish_title');
		$wyn_email_publish_body = ps ('wyn_email_publish_body');
	} else {
		if (!isset ($wyn_email_publish_address)) {
			$wyn_email_publish_address = '';
		}
		if (!isset ($wyn_email_publish_title)) {
			$wyn_email_publish_title = '%title%';
		}
		if (!isset ($wyn_email_publish_body)) {
			$wyn_email_publish_body = '<p>Orginal from <a href="%link%">%title%</a></p><p>%body%</p>';
		}
	}

	pagetop("Email Publish", $notify);

	set_pref ("wyn_email_publish_address", $wyn_email_publish_address, "wyn_email_publish", "2", "text_input");
	set_pref ("wyn_email_publish_title", $wyn_email_publish_title, "wyn_email_publish", "2", "text_input");
	set_pref ("wyn_email_publish_body", ($wyn_email_publish_body), "wyn_email_publish", "2", "text_input");

	echo form (
			startTable('edit') .

			tr (
				fLabelCell ("Target Email Address (';' separated)") .
				td (fInput ('text', 'wyn_email_publish_address', $wyn_email_publish_address, '', '', '', '40'))
				) .

			tr (
				fLabelCell ("You can customize the mail") .
				fLabelCell ("%title% for article title, %body% for article content, %author for author, %link% for permlink")
				) .

			tr (
				fLabelCell ("Mail title (%body% and %link% are NOT allowed here)") .
				td (fInput ('text', 'wyn_email_publish_title', $wyn_email_publish_title, '', '', '', '40'))
				) .

			tr (
				fLabelCell ("Mail body (plain html)") .
				td ("<textarea name='wyn_email_publish_body' cols='40' rows='10' " . $wyn_email_publish_body . "</textarea>")
				) .

			tr (
				td () .
				td (fInput ('submit', 'save', gTxt('save')))
				) .

			endTable () .

			eInput ('wyn_email_publish') .
			sInput ('save')
			);
}

# --- END PLUGIN CODE ---

?>